import React from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'
import {
  HashRouter as Router,
  Route,
  Link,
  NavLink,
  Redirect,
  Switch
} from 'react-router-dom'
import Goods from './components/goods'
import Cart from './components/cart'
import './css/app.scss'
import store from './redux/reducer'
import { mapStateToProps, mapDispatchToProps } from './redux/action'

//在渲染Dom的术后添加Provider组件  并且设置store属性  把数据往下传递
class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      list: []
    }
  }
  componentWillMount() {
    store.subscribe(() => {
      this.setState({
        list: this.props.cart
      })
    })
  }
  //统计数量
  count() {
    // console.log(this.props.cart)
    var num = 0
    for (var i in this.props.cart) {
      num += this.props.cart[i].num
    }
    return num
  }
  render() {
    return (
      <div>
        <ul className="navbar">
          <li>
            <NavLink to="/goods">商品</NavLink>
          </li>
          <li>
            <NavLink to="/cart">购物车</NavLink>
            <div className="xiao">{this.count()}</div>
          </li>
        </ul>
        <div className="show">
          <Switch>
            <Route path="/goods" component={Goods} />
            <Route path="/cart" component={Cart} />
            <Redirect from="/" to="/goods" />
          </Switch>
        </div>
      </div>
    )
  }
}
App = connect(
  mapStateToProps,
  mapDispatchToProps
)(App)

ReactDOM.render(
  <Provider store={store}>
    <Router>
      <Switch>
        <Route path="/" component={App} />
      </Switch>
    </Router>
  </Provider>,
  document.getElementById('app')
)
